package com.avic.rong.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.activity.AnLiShareActivity;
import com.avic.rong.activity.product.StandardServiceActivity;
import com.avic.rong.adapter.show.BigRecommecdAdapter;
import com.avic.rong.adapter.show.ChannedAdapter;
import com.avic.rong.adapter.show.ShowBannerAdapter;
import com.avic.rong.api.RecommendApi;
import com.avic.rong.bean.show_bean.ChannelContent;
import com.avic.rong.bean.show_bean.EsInfoBean;
import com.avic.rong.bean.show_bean.ShowBean;
import com.avic.rong.course.showapi.ChannelContentApi;
import com.avic.rong.fragment.fragmentshop.api.ShopBannerBeanApi;
import com.avic.rong.fragment.fragmentshop.bean.ShopBannerBean;
import com.avic.rong.fragment.showapi.EsInfoApi;
import com.avic.rong.goodsSort.activity.GoodsSortActivity;
import com.avic.rong.goodsSort.activity.secondListActivity.GoodsSortBzActivity;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.SkipUtils;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.library.banner.BannerLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.AppUtils;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

/**
 * 首页--推荐
 */
@SuppressLint("ValidFragment")
public class FragmentRecommend extends Fragment implements OnRefreshListener, OnLoadMoreListener {


    public SmartRefreshLayout refreshLayout;
    private String mTitle = ConstantsUtils.EMPTY_STR;
    private String mCodeString = "tj";
    public boolean isRefresh = false;
    public RecyclerView recyclerView;
    private Context mContext;
    private BigRecommecdAdapter bigRecommecdAdapter;
    private ArrayList<ChannelContent> channelList = new ArrayList<>();
    private List<ShopBannerBean.AdvertismentListBean> bannerListAll = new ArrayList<>();
    private List<String> bannerList = new ArrayList<>();
    private List<ShowBean> recommendList = new ArrayList<>();
    private ChannedAdapter channedAdapter;
    private RecommendApi recommendApi;
    private ChannelContentApi channelContentApi;

    private LoadingLayout loading_layout;
    private EsInfoApi esInfoApi;
    private ShopBannerBeanApi shopBannerBeanApi;

    private ShowBannerAdapter showBannerAdapter;
    private TextView shopTextGJB;
    private TextView shopTextGB;
    private TextView shopTextHB;
    private TextView shopTextQJ;
    private TextView shopTextJJF;
    private TextView shopTextJJG;
    private LinearLayout anliUp;
    private BannerLayout recommendBanner;
    private TextView standardAll;
    private TextView standardHat;
    private TextView standardNew;
    private TextView standardFuwu;
    private LinearLayout standardTu;
    private LinearLayout gjbButton;
    private LinearLayout hbButton;
    private LinearLayout gbButton;
    private LinearLayout jjgButton;
    private LinearLayout jjfButton;
    private LinearLayout qjButton;
    private LinearLayout standardTiao1;
    private LinearLayout xinxihua;
    public LinearLayoutManager linearLayoutManager;
//    public NestedScrollView nestedScrollView;
    private int currentPageNumber = 1;


    public FragmentRecommend() {
    }

    public static FragmentRecommend getInstance(String code, String title, Context context) {
        FragmentRecommend sf = new FragmentRecommend();
        sf.mContext = context;
        sf.mTitle = title;
        sf.mCodeString = code;
        return sf;
    }

    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }

    @Override
    public void onResume() {
        GSYVideoManager.onResume();
        super.onResume();
    }

    View fragmentView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        if (fragmentView != null){
            ViewGroup parent = (ViewGroup)fragmentView.getParent();
            if (parent != null){
                parent.removeView(fragmentView);
            }
            return fragmentView;
        }

         fragmentView = inflater.inflate(R.layout.fragment_recommand, container, false);



        initView(fragmentView);
        Logger.i("-----------------------onCreateView" + mTitle);
        return fragmentView;
    }

    @Override
    public void onStart() {
        super.onStart();
        initData();
        Logger.i("---------------------------------onStart" + mTitle);
    }

    //    protected int getContentViewId() {
//        return R.layout.fragment_recommand;
//    }


    protected void initView(View fragmentView) {
        loading_layout = fragmentView.findViewById(R.id.loading_layout);
        refreshLayout = fragmentView.findViewById(R.id.refreshLayout);
        recommendBanner = (BannerLayout) fragmentView.findViewById(R.id.recommend_banner);
        standardAll = (TextView) fragmentView.findViewById(R.id.standard_all);
        standardHat = (TextView) fragmentView.findViewById(R.id.standard_hat);
        standardNew = (TextView) fragmentView.findViewById(R.id.standard_new);
        standardFuwu = (TextView) fragmentView.findViewById(R.id.standard_fuwu);
        standardTu = (LinearLayout) fragmentView.findViewById(R.id.standard_tu);
        shopTextGJB = (TextView) fragmentView.findViewById(R.id.shop_text_GJB);
        gjbButton = (LinearLayout) fragmentView.findViewById(R.id.gjb_button);
        shopTextGB = (TextView) fragmentView.findViewById(R.id.shop_text_GB);
        hbButton = (LinearLayout) fragmentView.findViewById(R.id.hb_button);
        shopTextHB = (TextView) fragmentView.findViewById(R.id.shop_text_HB);
        gbButton = (LinearLayout) fragmentView.findViewById(R.id.gb_button);
        shopTextQJ = (TextView) fragmentView.findViewById(R.id.shop_text_QJ);
        jjgButton = (LinearLayout) fragmentView.findViewById(R.id.jjg_button);
        shopTextJJF = (TextView) fragmentView.findViewById(R.id.shop_text_JJF);
        jjfButton = (LinearLayout) fragmentView.findViewById(R.id.jjf_button);
        shopTextJJG = (TextView) fragmentView.findViewById(R.id.shop_text_JJG);
        qjButton = (LinearLayout) fragmentView.findViewById(R.id.qj_button);
        standardTiao1 = (LinearLayout) fragmentView.findViewById(R.id.standard_tiao1);
        anliUp = (LinearLayout) fragmentView.findViewById(R.id.anli_up);
        xinxihua = (LinearLayout) fragmentView.findViewById(R.id.xinxihua);
        recyclerView = (RecyclerView) fragmentView.findViewById(R.id.recyclerView);
        refreshLayout = (SmartRefreshLayout) fragmentView.findViewById(R.id.refreshLayout);

        recommendList.clear();
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);

        channedAdapter = new ChannedAdapter(getActivity());
        showBannerAdapter = new ShowBannerAdapter(getContext(), bannerList);//轮播图
        bigRecommecdAdapter = new BigRecommecdAdapter(getActivity());

        linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);

//        channelContentApi = new ChannelContentApi((MainActivity) getContext(), channelContentHttpListener, "");
//        loading_layout.hideReturnButton();

        //监听滚动
//        nestedScrollView = fragmentView.findViewById(R.id.nest_scrollview);
//        nestedScrollView.setOnScrollChangeListener(new RocketOnScrollListener(((MainActivity) getActivity())));

//        initData();
    }


    private void initData() {
        if (mTitle.equals("标准化")) {
            recommendBanner.setVisibility(View.VISIBLE);
            standardTu.setVisibility(View.VISIBLE);
            standardTiao1.setVisibility(View.VISIBLE);
            xinxihua.setVisibility(View.GONE);
        } else if (mTitle.equals("生产")) {
            recommendBanner.setVisibility(View.VISIBLE);
            standardTu.setVisibility(View.GONE);
            standardTiao1.setVisibility(View.GONE);
            xinxihua.setVisibility(View.GONE);
        } else if (mTitle.equals("质量")) {
            recommendBanner.setVisibility(View.VISIBLE);
            standardTu.setVisibility(View.GONE);
            standardTiao1.setVisibility(View.GONE);
            xinxihua.setVisibility(View.GONE);
        } else if (mTitle.equals("信息化")) {
            recommendBanner.setVisibility(View.VISIBLE);
            xinxihua.setVisibility(View.VISIBLE);
            standardTu.setVisibility(View.GONE);
            standardTiao1.setVisibility(View.GONE);
        } else {
            recommendBanner.setVisibility(View.GONE);
            standardTu.setVisibility(View.GONE);
            standardTiao1.setVisibility(View.GONE);
            xinxihua.setVisibility(View.GONE);
        }


        //加载数据
        bannerListAll.clear();
        //根据不同的标题展示不同的数据
        if (mTitle.equals("推荐")) {
            recyclerView.setAdapter(bigRecommecdAdapter);
            recommendApi = new RecommendApi((MainActivity) getContext(), recommendHttpOnNextListener, SharedPreferencesUtil.getLoginToken());
            recommendApi.setCache(false);
            recommendApi.setPageNo(currentPageNumber);
            HttpManager.getInstance().doHttpDeal(recommendApi);

//            loading_layout.hideReturnButton();
//            loading_layout.setStatus(LoadingLayout.LOADING);
//            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
//                @Override
//                public void onReload(View v) {
//                    loading_layout.setStatus(loading_layout.LOADING);
//                    HttpManager.getInstance().doHttpDeal(recommendApi);
//                }
//
//                @Override
//                public void onReturn(View v) {
//                }
//            });
        } else {
            if (mTitle.equals("生产")) {
                //轮播图
                shopBannerBeanApi = new ShopBannerBeanApi((MainActivity) getContext(), shopBannerBeanListener, ConstantsUtils.ADV_yield_TOP);
                HttpManager.getInstance().doHttpDeal(shopBannerBeanApi);

            } else if (mTitle.equals("信息化")) {
                //轮播图
                shopBannerBeanApi = new ShopBannerBeanApi((MainActivity) getContext(), shopBannerBeanListener, ConstantsUtils.ADV_INFO_TOP);
                HttpManager.getInstance().doHttpDeal(shopBannerBeanApi);

            } else if (mTitle.equals("质量")) {
                //轮播图
                shopBannerBeanApi = new ShopBannerBeanApi((MainActivity) getContext(), shopBannerBeanListener, ConstantsUtils.ADV_quality_TOP);
                HttpManager.getInstance().doHttpDeal(shopBannerBeanApi);

            } else if (mTitle.equals("标准化")) {
                //轮播图
                shopBannerBeanApi = new ShopBannerBeanApi((MainActivity) getContext(), shopBannerBeanListener, ConstantsUtils.ADV_STANDARD_TOP);
                HttpManager.getInstance().doHttpDeal(shopBannerBeanApi);

            }

            recyclerView.setAdapter(channedAdapter);

            //请求列表
            Logger.i("------------------------------net");
            channelContentApi = new ChannelContentApi((MainActivity) getContext(), channelContentHttpListener, mCodeString);
            channelContentApi.setPageNo(currentPageNumber);
            HttpManager.getInstance().doHttpDeal(channelContentApi);

//            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
//                @Override
//                public void onReload(View v) {
//                    loading_layout.setStatus(loading_layout.LOADING);
//                    HttpManager.getInstance().doHttpDeal(channelContentApi);
//                    if (shopBannerBeanApi != null) {
//                        HttpManager.getInstance().doHttpDeal(shopBannerBeanApi);
//                    }
//                }
//
//                @Override
//                public void onReturn(View v) {
//
//                }
//            });
        }
//        loading_layout.setStatus(LoadingLayout.LOADING);
    }

    //推荐
    HttpOnNextListener<BaseResultEntity> recommendHttpOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {

            if (!ConstantsUtils.STATUS_SUCCESS_200.equals(baseResultEntity.getCode())) {
                loading_layout.setStatus(LoadingLayout.ERROR);
                return;
            }

            loading_layout.setStatus(LoadingLayout.SUCCESS);
            if (isRefresh) {
                recommendList.clear();
            }

            recommendList.addAll((ArrayList<ShowBean>) baseResultEntity.getData());
            bigRecommecdAdapter.setBean(recommendList);

            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    //
    //下面是各频道文章的数据回调
    HttpOnNextListener<BaseResultEntity> channelContentHttpListener = new HttpOnNextListener<BaseResultEntity>() {

        @Override
        public void onNext(BaseResultEntity baseResultEntity) {

            if (!ConstantsUtils.STATUS_SUCCESS_200.equals(baseResultEntity.getCode())) {
                loading_layout.setStatus(LoadingLayout.ERROR);
                return;
            }

            loading_layout.setStatus(LoadingLayout.SUCCESS);
            if (isRefresh) {
                channelList.clear();
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }

            List<ChannelContent> data = (List<ChannelContent>) baseResultEntity.getData();
            if (data != null) {
                channelList.addAll(data);
            }

            //请求阅读数等附加信息
            String contIds = "";
            for (int i = 0; i < channelList.size(); i++) {
                if (channelList.get(i) != null) {
                    for (int i1 = 0; i1 < channelList.get(i).getDataX().size(); i1++) {
                        int contId = channelList.get(i).getDataX().get(i1).getId();
                        contIds += contId + ",";
                    }
                }
            }
            if (contIds.length() > 0) {
                contIds = contIds.substring(0, contIds.length() - 1);
            }
            esInfoApi = new EsInfoApi((MainActivity) getActivity(), ensInOnNextListener, contIds);
            HttpManager.getInstance().doHttpDeal(esInfoApi);
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            loading_layout.setStatus(LoadingLayout.ERROR);
            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
        }
    };



    //搜索补全接口
    HttpOnNextListener<BaseResultEntity> ensInOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {

            if (!ConstantsUtils.STATUS_SUCCESS_200.equals(baseResultEntity.getCode())) {
                loading_layout.setStatus(LoadingLayout.ERROR);
                return;
            }
            ArrayList<EsInfoBean> esInfoBean = (ArrayList<EsInfoBean>) baseResultEntity.getData();
            channedAdapter.setBean(channelList);
            channedAdapter.setEsInfoBeans(esInfoBean);
            channedAdapter.notifyDataSetChanged();

            loading_layout.setStatus(LoadingLayout.SUCCESS);
            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            loading_layout.setStatus(LoadingLayout.ERROR);
            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
        }
    };
    //轮播监听
    //获取商城轮播图数据监听
    HttpOnNextListener shopBannerBeanListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
//                ToastTools.showToast(getContext(), "商品banner：" + subjects.getMsg());
                return;
            }
            bannerListAll.clear();
            bannerList.clear();
            ShopBannerBean shopBannerBean = (ShopBannerBean) subjects.getData();
            List<ShopBannerBean.AdvertismentListBean> advertismentList = shopBannerBean.getAdvertismentList();
            bannerListAll.addAll(advertismentList);

            for (int i = 0; i < bannerListAll.size(); i++) {
                bannerList.add(bannerListAll.get(i).getContent());
                Log.e("cjx", "shopbannerlist:" + bannerListAll.get(i).getContent());
            }

            showBannerAdapter.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    Logger.i("------------" + "点击了第  " + position + "  项");
                    String bannerUrl = AppUtils.COURSE_IMAGE_URL + bannerListAll.get(position).getContent();
                    SkipUtils.startSkipDetailIntent(getContext(), bannerListAll.get(position).getUrl(), bannerUrl);
                }
            });
            recommendBanner.setAdapter(showBannerAdapter);
            recommendBanner.setAutoPlayDuration(5000);
            recommendBanner.setAutoPlaying(true);
        }


        @Override
        public void onError(final Throwable e) {

        }
    };

//    @OnClick({R.id.anli_up, R.id.standard_all, R.id.okan, R.id.standard_hat, R.id.standard_new, R.id.standard_fuwu, R.id.gjb_button, R.id.hb_button, R.id.gb_button, R.id.jjg_button, R.id.jjf_button, R.id.qj_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.anli_up://案例分享
                startActivity(new Intent(getActivity(), AnLiShareActivity.class));
                break;
            case R.id.standard_all:
                startActivity(GoodsSortActivity.getIntent(getContext()));
                break;
            case R.id.standard_hat:
                startActivity(GoodsSortBzActivity.getIntent(getContext(), 1, 3, null, null));
                break;
            case R.id.standard_new:
                startActivity(GoodsSortBzActivity.getIntent(getContext(), 1, 1, null, null));
                break;
            case R.id.standard_fuwu:
                Intent intent4 = new Intent(getActivity(), StandardServiceActivity.class);
                startActivity(intent4);
                break;
            case R.id.gjb_button:
                startActivity(GoodsSortBzActivity.getIntent(getContext(), 1, "gjb"));
                break;
            case R.id.hb_button:
                startActivity(GoodsSortBzActivity.getIntent(getContext(), 1, "hb"));
                break;
            case R.id.gb_button:
                startActivity(GoodsSortBzActivity.getIntent(getContext(), 1, "gb"));
                break;
            case R.id.jjg_button:
                startActivity(GoodsSortBzActivity.getIntent(getContext(), 1, "jjg"));
                break;
            case R.id.jjf_button:
                startActivity(GoodsSortBzActivity.getIntent(getContext(), 1, "jjf"));
                break;
            case R.id.qj_button:
                startActivity(GoodsSortBzActivity.getIntent(getContext(), 1, "qj"));
                break;
            case R.id.okan://解决方案
                startActivity(GoodsSortBzActivity.getIntent(getActivity(), 5, 0, "460", null));
                break;
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        isRefresh = true;
        currentPageNumber = 1;
        if (mTitle.equals("推荐")) {
            recommendList.clear();
            recommendApi.setPageNo(currentPageNumber);
            HttpManager.getInstance().doHttpDeal(recommendApi);
        } else {
            channelList.clear();
            channelContentApi.setPageNo(currentPageNumber);
            HttpManager.getInstance().doHttpDeal(channelContentApi);

        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        isRefresh = false;
        currentPageNumber = currentPageNumber + 1;
        if (mTitle.equals("推荐")) {
            recommendApi.setPageNo(currentPageNumber);
            HttpManager.getInstance().doHttpDeal(recommendApi);
        } else {
            channelContentApi.setPageNo(currentPageNumber);
            HttpManager.getInstance().doHttpDeal(channelContentApi);

        }
    }


}